package queuego

//使用go语言实现队列数据结构
//先进先出

type Queue struct {
	Data []any
	Head int
	Tail int
	Size int
}

func NewQueue() *Queue {
	queue := Queue{Head: 0, Tail: 0, Size: 0}
	queue.Data = make([]any, 10)
	return &queue
}

func (receiver *Queue) Push(data interface{}) {
	receiver.CapacityExpansion()
	receiver.Data[receiver.Tail] = data
	if receiver.Tail >= len(receiver.Data)-1 {
		receiver.Tail = 0
	} else {
		receiver.Tail++
	}
	receiver.Size++
}

func (receiver *Queue) Pop() (data interface{}) {
	if receiver.Size == 0 {
		return nil
	}
	d := receiver.Data[receiver.Head]
	receiver.Data[receiver.Head] = nil
	if receiver.Head >= len(receiver.Data)-1 {
		receiver.Head = 0
	} else {
		receiver.Head++
	}
	receiver.Size--
	return d
}

func (receiver *Queue) CapacityExpansion() {
	le := len(receiver.Data)
	if receiver.Size < le {
		return
	}
	newData := make([]any, le*2)
	oldData := receiver.Data
	newHead := 0
	newTail := 0
	for i := receiver.Head; i < le; i++ {
		newData[newTail] = oldData[i]
		newTail++
	}
	if receiver.Head >= receiver.Tail {
		for i := 0; i < receiver.Tail; i++ {
			newData[newTail] = oldData[i]
			newTail++
		}
	}
	receiver.Head = newHead
	receiver.Tail = newTail
	receiver.Data = newData

}
